package com.zhkj.txg.module.member.ui

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.txg.R
import com.zhkj.txg.module.home.ui.MainActivity
import com.zhkj.txg.module.member.entity.MemberProductUIEntity
import com.zhkj.txg.module.member.vm.MemberCardViewModel
import kotlinx.android.synthetic.main.activity_member_pay.*

class MemberPayActivity : ViewModelActivity<MemberCardViewModel>() {
    companion object {
        private val PRODUCT = "product"
        private val INVITED_CODE = "invited"
        fun start(activity: Activity, uiEntity: MemberProductUIEntity, inviteCode: String) {
            val intent = Intent(activity, MemberPayActivity::class.java).putExtra(PRODUCT, uiEntity)
                .putExtra(INVITED_CODE, inviteCode)
            activity.startActivity(intent)
        }
    }

    private val payFragment: MemberPayFragment by lazy { MemberPayFragment() }
    private val paySuccessFragment: MemberPaySuccessFragment by lazy { MemberPaySuccessFragment() }

    override fun setViewModel(): MemberCardViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleMemberPay
    override val layoutResId: Int = R.layout.activity_member_pay

    override fun initUI() {
        viewModel.productUIEntity = intent.getSerializableExtra(PRODUCT) as MemberProductUIEntity
        viewModel.inviteCode = intent.getStringExtra(INVITED_CODE)
        showFragment(payFragment)
    }

    override fun initViewModel() {
        viewModel.fragmentChangeLiveData.observe(this, Observer { if (it) showFragment(paySuccessFragment) })
    }

    override fun onBackPressed() {
        if (supportFragmentManager.fragments.size > 1) { // 有多个页面，说明支付成功，则跳转回首页
            val intent = Intent(this, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
            startActivity(intent)
        } else super.onBackPressed()
    }

    private fun showFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction().apply {
            supportFragmentManager.fragments.forEach { hide(it) }
            if (!fragment.isAdded) add(R.id.containerMember, fragment)
                .setMaxLifecycle(fragment, Lifecycle.State.RESUMED)
        }.show(fragment).commit()
    }
}